import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Device {
  id: string
  name: string
  type: 'linux' | 'windows' | 'docker' | 'mobile'
  status: 'online' | 'offline' | 'busy'
  ipAddress: string
  port: number
  username?: string
  authType: 'ssh-key' | 'password'
  description?: string
  specs: {
    cpu: string
    memory: string
    os: string
  }
  performance: {
    cpuUsage: number
    memoryUsage: number
    diskUsage?: number
  }
  lastConnected: string
  createdAt: string
}

export interface DeviceProcess {
  pid: number
  name: string
  cpuUsage: number
  memoryUsage: number
  status: 'running' | 'stopped' | 'sleeping'
  runtime: string
  command?: string
}

export interface DeviceTest {
  id: string
  deviceId: string
  testType: 'connection' | 'performance' | 'stress' | 'stability'
  status: 'pending' | 'running' | 'completed' | 'failed'
  results: {
    connection?: {
      status: boolean
      latency: number
    }
    performance?: {
      score: number
      details: string
    }
    stress?: {
      status: boolean
      maxLoad: number
    }
    stability?: {
      status: boolean
      uptime: number
    }
  }
  startTime: string
  endTime?: string
  logs: string[]
}

export const useDeviceStore = defineStore('device', () => {
  // 状态
  const devices = ref<Device[]>([
    {
      id: 'server-001',
      name: '测试服务器-001',
      type: 'linux',
      status: 'online',
      ipAddress: '192.168.1.101',
      port: 22,
      username: 'root',
      authType: 'ssh-key',
      description: '主要测试服务器',
      specs: {
        cpu: 'Intel Xeon E5-2680 v4',
        memory: '16GB DDR4',
        os: 'Ubuntu 20.04 LTS'
      },
      performance: {
        cpuUsage: 35,
        memoryUsage: 68,
        diskUsage: 45
      },
      lastConnected: '2分钟前',
      createdAt: '2024-01-10 08:00:00'
    },
    {
      id: 'server-002',
      name: '测试服务器-002',
      type: 'linux',
      status: 'busy',
      ipAddress: '192.168.1.102',
      port: 22,
      username: 'root',
      authType: 'ssh-key',
      description: '性能测试专用服务器',
      specs: {
        cpu: 'Intel Xeon Gold 6248',
        memory: '32GB DDR4',
        os: 'CentOS 8'
      },
      performance: {
        cpuUsage: 85,
        memoryUsage: 72,
        diskUsage: 38
      },
      lastConnected: '5分钟前',
      createdAt: '2024-01-10 08:00:00'
    },
    {
      id: 'docker-cluster',
      name: 'Docker集群',
      type: 'docker',
      status: 'online',
      ipAddress: '192.168.1.200',
      port: 2376,
      authType: 'ssh-key',
      description: '容器化测试环境',
      specs: {
        cpu: '集群 24 核心',
        memory: '64GB',
        os: 'Docker Swarm'
      },
      performance: {
        cpuUsage: 42,
        memoryUsage: 55,
        diskUsage: 60
      },
      lastConnected: '1分钟前',
      createdAt: '2024-01-12 10:00:00'
    }
  ])

  const deviceProcesses = ref<Record<string, DeviceProcess[]>>({
    'server-001': [
      {
        pid: 12345,
        name: 'web_test_runner.py',
        cpuUsage: 25.3,
        memoryUsage: 12.8,
        status: 'running',
        runtime: '05:23',
        command: 'python web_test_runner.py --config=login_test'
      },
      {
        pid: 12346,
        name: 'api_performance_test',
        cpuUsage: 8.1,
        memoryUsage: 5.2,
        status: 'running',
        runtime: '02:45',
        command: './api_performance_test --threads=10'
      }
    ]
  })

  const deviceTests = ref<DeviceTest[]>([
    {
      id: 'test-001',
      deviceId: 'server-001',
      testType: 'connection',
      status: 'completed',
      results: {
        connection: {
          status: true,
          latency: 2
        }
      },
      startTime: '2024-01-15 14:00:00',
      endTime: '2024-01-15 14:00:05',
      logs: [
        '[14:00:00] 开始连接测试',
        '[14:00:02] 连接成功',
        '[14:00:05] 测试完成'
      ]
    }
  ])

  // 计算属性
  const onlineDevices = computed(() => 
    devices.value.filter(device => device.status === 'online')
  )

  const offlineDevices = computed(() => 
    devices.value.filter(device => device.status === 'offline')
  )

  const busyDevices = computed(() => 
    devices.value.filter(device => device.status === 'busy')
  )

  const deviceStats = computed(() => ({
    total: devices.value.length,
    online: onlineDevices.value.length,
    offline: offlineDevices.value.length,
    busy: busyDevices.value.length
  }))

  const averagePerformance = computed(() => {
    if (devices.value.length === 0) return { cpu: 0, memory: 0, disk: 0 }
    
    const total = devices.value.reduce(
      (acc, device) => ({
        cpu: acc.cpu + device.performance.cpuUsage,
        memory: acc.memory + device.performance.memoryUsage,
        disk: acc.disk + (device.performance.diskUsage || 0)
      }),
      { cpu: 0, memory: 0, disk: 0 }
    )
    
    return {
      cpu: Math.round(total.cpu / devices.value.length),
      memory: Math.round(total.memory / devices.value.length),
      disk: Math.round(total.disk / devices.value.length)
    }
  })

  // 动作
  const addDevice = (device: Omit<Device, 'id' | 'createdAt'>) => {
    const newDevice: Device = {
      ...device,
      id: `device-${Date.now()}`,
      createdAt: new Date().toISOString()
    }
    devices.value.push(newDevice)
    return newDevice
  }

  const updateDevice = (id: string, updates: Partial<Device>) => {
    const index = devices.value.findIndex(device => device.id === id)
    if (index > -1) {
      devices.value[index] = { ...devices.value[index], ...updates }
      return devices.value[index]
    }
    return null
  }

  const deleteDevice = (id: string) => {
    const index = devices.value.findIndex(device => device.id === id)
    if (index > -1) {
      devices.value.splice(index, 1)
      return true
    }
    return false
  }

  const getDeviceById = (id: string) => {
    return devices.value.find(device => device.id === id)
  }

  const updateDevicePerformance = (id: string, performance: Partial<Device['performance']>) => {
    const device = getDeviceById(id)
    if (device) {
      device.performance = { ...device.performance, ...performance }
      device.lastConnected = '刚刚'
    }
  }

  const getDeviceProcesses = (deviceId: string) => {
    return deviceProcesses.value[deviceId] || []
  }

  const updateDeviceProcesses = (deviceId: string, processes: DeviceProcess[]) => {
    deviceProcesses.value[deviceId] = processes
  }

  const killProcess = (deviceId: string, pid: number) => {
    const processes = deviceProcesses.value[deviceId]
    if (processes) {
      const index = processes.findIndex(p => p.pid === pid)
      if (index > -1) {
        processes[index].status = 'stopped'
      }
    }
  }

  const addDeviceTest = (test: Omit<DeviceTest, 'id'>) => {
    const newTest: DeviceTest = {
      ...test,
      id: `test-${Date.now()}`
    }
    deviceTests.value.push(newTest)
    return newTest
  }

  const updateDeviceTest = (id: string, updates: Partial<DeviceTest>) => {
    const index = deviceTests.value.findIndex(test => test.id === id)
    if (index > -1) {
      deviceTests.value[index] = { ...deviceTests.value[index], ...updates }
      return deviceTests.value[index]
    }
    return null
  }

  const getDeviceTests = (deviceId: string) => {
    return deviceTests.value.filter(test => test.deviceId === deviceId)
  }

  return {
    // 状态
    devices,
    deviceProcesses,
    deviceTests,
    
    // 计算属性
    onlineDevices,
    offlineDevices,
    busyDevices,
    deviceStats,
    averagePerformance,
    
    // 动作
    addDevice,
    updateDevice,
    deleteDevice,
    getDeviceById,
    updateDevicePerformance,
    getDeviceProcesses,
    updateDeviceProcesses,
    killProcess,
    addDeviceTest,
    updateDeviceTest,
    getDeviceTests
  }
})

